package com.poobo.bailianlong.utile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;

import android.os.Environment;
import android.util.Log;

public class DownConfigure {
	final private String SERVERURL = "http://www.biliongjoy.com:8080/EquipmentSys/equipment/findByEquipmentNumber.html";
//	final private String SERVERURL = "http://192.168.1.72:8080/EquipmentSys/equipment/findByEquipmentNumber.html";
	private String DEVICE_ID = "";
	private URL url = null; 
	private String configureurl = "";
	String newFilePath = Environment.getExternalStorageDirectory() + "/" + "/" + "voa/configure.txt";
	String oldFilePath = Environment.getExternalStorageDirectory() + "/" + "/" + "voa/configurebak.txt";	
	long lastStartTime = 0;
	
	
	public DownConfigure(String deviceId){
		DEVICE_ID = deviceId;
		Log.e("Bililong", "deviceId" + DEVICE_ID);
	}
	
	/**
	 * 下载配置文件
	 * @param 
	 * @return
	 * 0： 下载成功
	 * -1： 配置文件为空或不完整
	 * -2： 设备未启用
	 * -3： 未获取到任何内容
	 */
	public int startDownload(){	
//		if(lastStartTime == 0 || (System.currentTimeMillis()-lastStartTime) > 1000){
//			lastStartTime = System.currentTimeMillis();
//			
//		}
		String[] configureInfo = new String[4]; 
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
    		newFilePath = Environment.getExternalStorageDirectory() + "/" + "/" + "voa/configure.txt";
    		oldFilePath = Environment.getExternalStorageDirectory() + "/" + "/" + "voa/configurebak.txt";
    		File dirFile = new File(Environment.getExternalStorageDirectory() + "/" + "/voa");
    		if(!dirFile.exists()){
    			File dir = new File(Environment.getExternalStorageDirectory() + "/" + "/voa");				
    			dir.mkdir();  		
    		}
		}else{
			newFilePath = Environment.getRootDirectory() + "/" + "/" + "voa/configure.txt";
    		oldFilePath = Environment.getRootDirectory() + "/" + "/" + "voa/configurebak.txt";
    		
    		File dirFile = new File(Environment.getRootDirectory() + "/" + "/voa/");
    		if(!dirFile.exists()){
    			File dir = new File(Environment.getRootDirectory() + "/" + "/voa/");				
    			dir.mkdir();
    		}
    		
		}
		
		configureInfo = getConfigureurl(DEVICE_ID);
		if(configureInfo[0] == null){
			return -3;
		}
		Log.e("Bililong", "configureInfo:" + configureInfo[0]);
		if(configureInfo[0].equals("unable") && configureInfo[1].equals("unable")){
			return -2;
		}
		configureurl = configureInfo[3];
		
		Log.d("Bililong","configureurl:"+configureurl);
	
		String resourceString = download();	
		if(resourceString == ""){
			Log.d("Bililong","配置文件为空");
			return -1;
		}
		
		resourceString = resourceString + configureInfo[0] + "|" + configureInfo[1] + "|" + configureInfo[2] +"&nextline&";
		Log.v("Bililong","resourceString: "+resourceString);	
		resourceString = resourceString.replaceAll("[\\n\\r]", "");		
		String[] configtxt = resourceString.toString().split("&nextline&");
		Log.v("Bililong","configtxt[0]:"+configtxt[0]);
		
		String[] configtxtLengthArray = configtxt[0].replaceAll("[\\n\\r]", "").trim().split("\\|");	
		String configtxtLength = configtxtLengthArray[0];
//		Log.e("Bililong", "" + configtxtLength+"\n" + configtxt[5] +"__ \n" + configtxt[4] +"  __\n" + configtxt[3]
//				+ "  __\n 2:" + configtxt[2] + "  __\n 1:" + configtxt[1] +"\n 0:" + configtxt[0] );
		if(Integer.parseInt(configtxtLength) != configtxt.length - 3){
			Log.d("Bililong","文件不完整");
			return -1;
			
		}else{
			if(write(resourceString) == 0){
				return 0;
			}else{
				return -1;
			}
			
		}			
	}
	
	/** 
	* @Title: download 
	* @Description: 具体的下载配置文件
	*/
	public String download(){
		StringBuffer sb = new StringBuffer();
		String line = null;
		BufferedReader buffer = null;
		try {
			url = new URL(configureurl);						
			HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
			buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));
			while( (line = buffer.readLine()) != null){
				sb.append(line);
			}
			
		} 
		catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			try {
				if(buffer == null){					
				}else{
					buffer.close();
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	
	
	/** 
	* @Title: getConfigureurl 
	* @Description: 获取配置文档信息，包括配置文件url，默认游戏的url，名称，版本号 
	* @param @param deviceId
	* @param @return    设定文件 
	* @return String[]    返回类型 
	* @throws 
	*/
	public String[] getConfigureurl(String deviceId){

		StringBuffer sb = new StringBuffer();
		BufferedReader buffer = null;
		String line = null;
		String receivedString[] = new String[4];
		try {			
	        String message=URLEncoder.encode(deviceId, "UTF-8");
			String path =SERVERURL + "?DEVEICEID=" + message;
	        URL url =new URL(path);
	        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
	        conn.setConnectTimeout(5*1000);
	        InputStream inStream = conn.getInputStream();
	        buffer = new BufferedReader(new InputStreamReader(inStream));
			while( (line = buffer.readLine()) != null){
				sb.append(line);				
			}
			String receivedString1 = sb.toString();	
			Log.d("Bililong","the url content: "+receivedString1);
			receivedString1 = receivedString1.replaceAll("[\\n\\r]", "");	
			if(receivedString1.equals("unable")){
				receivedString[0]  = "unable";
				receivedString[1]  = "unable";
				receivedString[2]  = "unable";
				receivedString[3]  = "unable";
			}else{
				receivedString = receivedString1.toString().split(",");
			}
			
		} catch (MalformedURLException e) {
			e.printStackTrace();		
		} catch (SocketTimeoutException e) {
			Log.e("Bililong","SocketTimeoutException");
			e.printStackTrace();			
		}catch (IOException e) {
			e.printStackTrace();
			Log.e("Bililong","IOException");
		}
		catch (Exception e) {
			e.printStackTrace();
			Log.e("Bililong",e.getMessage(), e);
		}
		return receivedString;
	}
	
	public int write(String resourceString){
		Log.d("Bililong","write()");
		File oldFile = new File(oldFilePath);
		File newFile = new File(newFilePath);
		if(oldFile.exists()){
			oldFile.delete();					
		}		
		if(newFile.exists()){
			boolean flag = newFile.renameTo(oldFile);						
		}
							
		if(newFile.exists()){
			newFile.delete();					
		}					
		//write to configure.txt
		OutputStreamWriter osw = null;
		try {  
            osw = new OutputStreamWriter(new FileOutputStream(newFile), "UTF-8");  
            osw.write(resourceString); 
          	osw.flush();   
        } catch (Exception e) {  
            e.printStackTrace();  
            return -1;
        }  
        finally{  
            if(osw!=null)  
                try {  
                    osw.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
        } 
		return 0;
	}
}
